import axios from './axios'

const caches = {}

export class HttpRequest {
  constructor(baseURL) {
    this.baseURL = resolveBaseURL(baseURL)
  }

  post (url, params = {}, config) {
    config = config || {}
    config.baseURL = this.baseURL
    return axios.post(url, params, config)
  }

  get (url, config) {
    config = config || {}
    config.baseURL = this.baseURL
    return axios.get(url, config)
  }

  delete (url, params, config = {}) {
    config = config || {}
    config.baseURL = this.baseURL
    return axios.delete(url, params, config)
  }

  download (url, config = {}) {
    config = config || {}
    config.baseURL = this.baseURL
    return axios.download(url, config)
  }
}

export function create (baseURL) {
  baseURL = resolveBaseURL(baseURL)
  if (caches[baseURL]) {
    return caches[baseURL]
  }
  const instance = new HttpRequest(baseURL)
  caches[baseURL] = instance
  return instance
}

function resolveBaseURL (baseURL) {
  if (!baseURL) {
    return process.env.VUE_APP_API_BASE_URL
  }
  if (!baseURL.startsWith('http://') && !baseURL.startsWith('https://')) {
    baseURL = `${process.env.VUE_APP_API_BASE_URL}/${baseURL}`
  }
  return baseURL
}